package com.az.servicecommon.util;

import com.az.miaoapi.exception.BaseException;
import com.az.miaoapi.response.ResponseCode;
import com.az.miaoapi.response.ResponseResult;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@Slf4j
@RestControllerAdvice(annotations = BaseResponse.class)
public class GlobalAdvice implements ResponseBodyAdvice<Object> {


    @Override
    public boolean supports(@NonNull MethodParameter returnType, @NonNull Class converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(
            Object data,
            @NonNull MethodParameter returnType,
            @NonNull MediaType selectedContentType,
            @NonNull Class selectedConverterType,
            @NonNull ServerHttpRequest request,
            @NonNull ServerHttpResponse response
    ) {
        if (MediaType.APPLICATION_JSON.equals(selectedContentType)) {
            if (data instanceof ResponseResult) {
                return data;
            } else {

                return new ResponseResult(ResponseCode.SUCCESS, data);
            }
        }

        return new ResponseResult(ResponseCode.RESPONSE_FORMAT_ERROR, data);
    }

    /**
     * 处理未捕获的RuntimeException
     */
    @ExceptionHandler(RuntimeException.class)
    public ResponseResult handleRuntimeException(RuntimeException e){
        log.error("e: ", e);
        return new ResponseResult(ResponseCode.SERVICE_ERROR);
    }

    /**
     * 处理业务异常BaseException
     */
    @ExceptionHandler(BaseException.class)
    public ResponseResult handleBaseException(BaseException e){
        return new ResponseResult(e.getCode());
    }
}
